package com.jichaoyun.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jichaoyun.common.enums.MyExceptiontType;
import com.jichaoyun.common.ex.MyException;
import com.jichaoyun.model.entity.BalanceAlarm;
import com.jichaoyun.model.entity.StationInfo;

//import com.jichaoyun.model.entity.BalanceAlarm;

import com.jichaoyun.model.entity.LineInfo;
import com.jichaoyun.model.entity.User;
import com.jichaoyun.sys.mapper.BalanceAlarmMapper;
import com.jichaoyun.sys.mapper.LineInfoMapper;
import com.jichaoyun.sys.mapper.StationInfoMapper;
import com.jichaoyun.sys.mapper.UserMapper;
import com.jichaoyun.sys.service.IBalanceAlarmService;
import com.jichaoyun.sys.service.IStationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
* @author zhen
* @description 针对表【balanceAlarm】的数据库操作Service实现
* @createDate 2023-12-08 11:11:54
*/
@Service
public class BalanceAlarmServiceImpl extends ServiceImpl<BalanceAlarmMapper, BalanceAlarm>
    implements IBalanceAlarmService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private BalanceAlarmMapper balancealarmMapper;

    @Resource
    private StationInfoMapper stationInfoMapper;

    @Resource
    private LineInfoMapper lineInfoMapper;

    @Resource
    private IStationInfoService stationInfoService;

    /**
     * 余额报警信息已读接口
     * @param userId
     */
    @Override
    public void MakeAlarmRead(Integer id,Integer userId) {
        LambdaQueryWrapper<User> queryWrapper0 = new LambdaQueryWrapper<>();
        queryWrapper0.eq(User::getId,userId);
        User user = this.userMapper.selectOne(queryWrapper0);

        if(user.getUserRole() != 0){
            LambdaQueryWrapper<BalanceAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BalanceAlarm::getId,id);
            BalanceAlarm balanceAlarm = this.balancealarmMapper.selectOne(wrapper);
            balanceAlarm.setIsReadAdmin(true);
            this.balancealarmMapper.updateById(balanceAlarm);
        }else {
            LambdaQueryWrapper<BalanceAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BalanceAlarm::getId,id);
            BalanceAlarm balanceAlarm = this.balancealarmMapper.selectOne(wrapper);
            balanceAlarm.setIsRead(true);
            this.balancealarmMapper.updateById(balanceAlarm);
        }

    }
    /**
     * 全部余额报警信息已读接口
     * @param userId
     */
    @Override
    public void MakeAlarmRead(Integer userId) {

        LambdaQueryWrapper<User> queryWrapper0 = new LambdaQueryWrapper<>();
        queryWrapper0.eq(User::getId,userId);
        User user = this.userMapper.selectOne(queryWrapper0);

        if(user.getUserRole() != 0){
            LambdaQueryWrapper<BalanceAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BalanceAlarm::getIsReadAdmin,0);
            List<BalanceAlarm> BalanceAlarmList = this.balancealarmMapper.selectList(lambdaQueryWrapper);

            for(BalanceAlarm balanceAlarm:BalanceAlarmList){
                balanceAlarm.setIsReadAdmin(true);
                this.balancealarmMapper.updateById(balanceAlarm);
            }

        }else {
            LambdaQueryWrapper<StationInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StationInfo::getUserId,userId);
            List<StationInfo> stationInfoList = this.stationInfoMapper.selectList(queryWrapper);

            List<Integer> stationNoList = new ArrayList<>();
            for(StationInfo stationInfo:stationInfoList){
                stationNoList.add(stationInfo.getStationNo());
            }
            if(stationNoList.isEmpty()){
                throw new MyException(MyExceptiontType.Other,null);
            }

            LambdaQueryWrapper<BalanceAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(BalanceAlarm::getStationNo,stationNoList)
                              .eq(BalanceAlarm::getIsRead,0);
            List<BalanceAlarm> BalanceAlarmList = this.balancealarmMapper.selectList(lambdaQueryWrapper);

            for(BalanceAlarm balanceAlarm:BalanceAlarmList){
                balanceAlarm.setIsRead(true);
                this.balancealarmMapper.updateById(balanceAlarm);
            }
        }
    }
    /**
     * 查询未读的余额报警信息
     * @return
     */
    @Override
    public List<Map<String,Object>> pollingDb(Integer userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = this.userMapper.selectOne(queryWrapper);
        if(user.getUserRole() != 0) {
            //查询所有管理员未读的报警
            LambdaQueryWrapper<BalanceAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BalanceAlarm::getIsReadAdmin, 0).orderByAsc(BalanceAlarm::getId);
            List<BalanceAlarm> list = balancealarmMapper.selectList(wrapper);

            if (list != null) {
                List<Map<String, Object>> resList = new ArrayList<>();

                Map<Integer, String> map1 = new HashMap<>();
                Map<Integer,Integer> map2 = new HashMap<>();
                for (BalanceAlarm item : list) {
                    //一个站点的通讯报警只取最新的一条
                    map1.put(item.getStationNo(), item.getTime().toString());
                    map2.put(item.getStationNo(),item.getId());
                }
                for (Integer item : map1.keySet()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("报警类型", "余额报警");
                    map.put("报警站点", stationInfoService.getById(item).getStationName());
                    map.put("报警时间", map1.get(item));
                    map.put("id",map2.get(item));
                    resList.add(map);
                }
                return resList;
            }
        }
        else {
            LambdaQueryWrapper<StationInfo> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(StationInfo::getUserId,userId);
            List<StationInfo> stationInfoList = this.stationInfoMapper.selectList(queryWrapper1);

            List<Integer> stationNoList = new ArrayList<>();
            for(StationInfo stationInfo:stationInfoList){
                stationNoList.add(stationInfo.getStationNo());
            }

            //查询单个用户所有站点未读的报警
            LambdaQueryWrapper<BalanceAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BalanceAlarm::getIsRead,0)
                    .in(BalanceAlarm::getStationNo,stationNoList)
                    .orderByAsc(BalanceAlarm::getId);
            List<BalanceAlarm> list = balancealarmMapper.selectList(wrapper);

            if(list != null){
                List<Map<String,Object>> resList = new ArrayList<>();

                Map<Integer,Object> map1 = new HashMap<>();
                Map<Integer,Integer> map2 = new HashMap<>();
                for(BalanceAlarm item:list){
                    //一个站点的通讯报警只取最新的一条
                    map1.put(item.getStationNo(),item.getTime().toString());
                    map2.put(item.getStationNo(),item.getId());
                }
                for(Integer item : map1.keySet()){
                    Map<String, Object> map = new HashMap<>();
                    map.put("报警类型","余额报警");
                    map.put("报警站点",stationInfoService.getById(item).getStationName());
                    map.put("报警时间",map1.get(item));
                    map.put("id",map2.get(item));
                    resList.add(map);
                }
                return resList;
            }
        }
        return null;
    }

    private void getAccountByBalanceAlarmList(List<BalanceAlarm> balanceAlarmList, LinkedHashMap<String, Object> resMap) {
        //初始化所有的线路为0
        List<LineInfo> lineInfos = lineInfoMapper.selectList(null);
        for (LineInfo lineInfo : lineInfos) {
            String line_name =  lineInfo.getLineAlias();
            if(line_name==null ||line_name.equals("")){
                line_name = lineInfo.getLineName();
            }
            resMap.put(line_name,0);
        }

        //给每个路线的余额报警进行累计
        for (BalanceAlarm balancealarm : balanceAlarmList) {
            Integer station_no = balancealarm.getStationNo();
            String line_name =  lineInfoMapper.selectById(stationInfoMapper.selectById(station_no).getLineId()).getLineAlias();
            if(line_name==null ||line_name.equals("")){
                line_name = lineInfoMapper.selectById(stationInfoMapper.selectById(station_no).getLineId()).getLineName();
            }
            Integer old =(Integer) resMap.get(line_name);
            resMap.put(line_name,old+1);
        }

        //去掉值为0的resMap里面的键值对
        Iterator<Map.Entry<String, Object>> iterator = resMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            if ((Integer)entry.getValue() == 0) {
                iterator.remove();
            }
        }

        // 将resMap里面的每个值转化成其在所有余额报警中的占比，占比用百分比表示，百分比保留1位小数
        for (Map.Entry<String, Object> entry : resMap.entrySet()) {
            Integer value = (Integer) entry.getValue();
            Integer all = balanceAlarmList.size();
            resMap.put(entry.getKey(),String.format("%.1f",value*100f/all) + '%');
        }
    }



}




